#include"Socket.hpp"
#include<iostream>
#include <string>
#include"RedirTerminal.hpp"
RedirTermial rd;
struct ThreadData
{
    int fd;
    struct sockaddr_in peer;
};

//线程入口函数
void* Sender(void*argv)
{
    ThreadData*t1=static_cast<ThreadData*>(argv);
     //向服务器发送信息
    std::string line;
    while(true)
    {
    std::getline(std::cin,line);
   ssize_t n=sendto(t1->fd,line.c_str(),line.size(),0,(struct sockaddr*)&(t1->peer),sizeof(t1->peer));
    if(n<0)
    {
        printf("sendto error!!\n");
    }
    }
    return nullptr;
}
void* Recver(void*argv)
{   
    ThreadData*t1=static_cast<ThreadData*>(argv);
         char buffer[1024];

    while(true)
    {
        memset(buffer,0,sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len=sizeof(temp);
   ssize_t n= recvfrom(t1->fd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&temp,&len);
 if(n<0)
 {
    std::cout<<"recvfrom error!!"<<std::endl;
 }
 else if(n>0)
 {
    buffer[n]=0;
    std::cerr<<buffer<<std::endl;

 }
    }
   
    return nullptr;
}
int main()
{
    rd();
    Sock sockfd;
    sockfd.Socket();


    //对方ip 端口保存在 struct sockaddr_in 
    uint16_t serverport=8888;
    std::string serverip="127.0.0.1";

    //构建结构体传入线程
    ThreadData t1;
    t1.fd=sockfd.Fd();
    
    memset(&t1.peer,0,sizeof(t1.peer));
    t1.peer.sin_port=htons(serverport);
    t1.peer.sin_family=AF_INET;
    inet_pton(AF_INET,serverip.c_str(),&t1.peer.sin_addr);

    //创建线程执行读写任务
    pthread_t sendtd;
    pthread_create(&sendtd,nullptr,Sender,&t1);
pthread_t recvtd;
pthread_create(&recvtd,nullptr,Recver,&t1);

//等待线程
pthread_join(recvtd,nullptr);
pthread_join(sendtd,nullptr);
   close(t1.fd);
 
          return 0;
}